/**
 * 
 */
package com.effectiv.gooruda.mvc.controller;

import java.util.Locale;

import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.effectiv.gooruda.business.api.TenantService;
import com.effectiv.gooruda.domain.Tenant;

import com.effectiv.gooruda.mvc.argumentresolver.AjaxResponse;

/**
 * @author Dhrubo
 * 
 */
@Controller
@Slf4j
public class TenantController {

	@Autowired
	private TenantService tenantService;

	

	// OK - Fixed
	@RequestMapping(value = "/registration")
	public final String showRegisterDisplay(Model model) {
		Tenant tenant = BeanUtils.instantiate(Tenant.class);
		model.addAttribute("user", tenant);
		return "registration";
	}

	// OK - Fixed
	@RequestMapping(value = "/registeruser", method = RequestMethod.POST)
	public @ResponseBody
	AjaxResponse register(@Valid Tenant tenant, BindingResult result,
			AjaxResponse response, Locale locale) {
		log.info("------- Creating new tenant ---------");
		
		if (!result.hasErrors()) {
			log.info("tenant == {}", tenant);
			tenantService.register(tenant, locale);
			
			try{
				tenantService.sendMail(tenant, locale, "registration", "Welcome to Gooruda!");
			}
			catch(Exception e){
				//ignore but log
				log.error("Error occured while sending email", e);
			}
			
			response.setResult(tenant);
		} else {
			response.markValidationFailure(result.getFieldErrors());
		}

		return response;
	}

	@RequestMapping(value = "/activate")
	public final String activate(@RequestParam("user") String id, Model model,
			Locale locale) {
		Tenant tenant = tenantService.activate(id, locale);
		//TODO - Better error handling required, what if activation was unsuccessful or user was missing??
		try{
			tenantService.sendMail(tenant, locale, "activation", "Gooruda Account Activation");
		}
		catch(Exception e){
			//ignore but log
			log.error("Error occured while sending email", e);
		}

		model.addAttribute(tenant);

		return "activation";
	}

	@ExceptionHandler(DuplicateKeyException.class)
	@ResponseBody
	public AjaxResponse handleDuplicateKeyException(DuplicateKeyException ex) {

		AjaxResponse response = BeanUtils.instantiate(AjaxResponse.class);
		response.setStatus(AjaxResponse.ERROR);
		response.setMessage("User with the given email already exists. Please use another email.");

		return response;

	}

}
